package com.atguigu.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.entity.excel.SubjectData;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

public class SubjectDataListener extends AnalysisEventListener<SubjectData> {

private  SubjectMapper subjectMapper;

    public SubjectDataListener (SubjectMapper subjectMapper){
    this.subjectMapper =subjectMapper;
    }


    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        //一级标题和子标题存储在同一张表内，通过parent_id来区分是一级标题还是子标题
        //获取读取的对象的两级标题
        String levelOneClassify = subjectData.getLevelOneClassify();
        String levelTwoClassify = subjectData.getLevelTwoClassify();
        //判断数据库中是否存在一级标题，如果存在则不保存，反之则保存
        LambdaQueryWrapper<Subject> querywrapper = new LambdaQueryWrapper<>();
        querywrapper.eq(Subject::getTitle,levelOneClassify);
        querywrapper.eq(Subject::getParentId,0);
        Subject psubject = subjectMapper.selectOne(querywrapper);
        if (psubject==null){//如果查询出来是null则对数据库进行添加操作
            psubject =new Subject();
            psubject.setParentId("0");
            psubject.setTitle(levelOneClassify);
            psubject.setSort(0);
            subjectMapper.insert(psubject);
        }//反之不进行任何的操作
        //根据上面的subject中查询或者添加的返回的雪花算法的id，查询二级标题是否存在，如果不存在则进行保存
        querywrapper.clear();
        Subject subject = new Subject();
        querywrapper.eq(Subject::getParentId,psubject.getId());
        querywrapper.eq(Subject::getTitle,levelTwoClassify);
        Integer selectCount = subjectMapper.selectCount(querywrapper);
        if (selectCount==0) {//查询结果返回值等于0说明没有查询，需要添加
            subject.setParentId(psubject.getId());
            subject.setTitle(levelTwoClassify);
            subject.setSort(1);
            subjectMapper.insert(subject);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
